import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Alert,
  ActivityIndicator,
  Dimensions
} from 'react-native';
import { PieChart, LineChart, BarChart } from 'react-native-chart-kit';
import statisticsService from '../../services/statistics';

const { width: screenWidth } = Dimensions.get('window');

const StatisticsScreen = () => {
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState(null);
  const [chartType, setChartType] = useState('daily');

  useEffect(() => {
    loadStatistics();
  }, []);

  // 加载统计数据
  const loadStatistics = async () => {
    try {
      setLoading(true);
      
      // 确保统计服务已初始化
      await statisticsService.initialize();
      
      // 获取统计数据
      const usageStats = statisticsService.getUsageReport();
      setStats(usageStats);
      
      console.log('统计数据加载完成');
    } catch (error) {
      console.error('加载统计数据失败:', error);
      Alert.alert('错误', '加载统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 重置统计数据
  const handleResetStats = () => {
    Alert.alert(
      '重置统计',
      '确定要重置所有统计数据吗？此操作不可恢复。',
      [
        { text: '取消', style: 'cancel' },
        { 
          text: '确定', 
          onPress: async () => {
            try {
              setLoading(true);
              await statisticsService.resetData();
              await loadStatistics();
              Alert.alert('成功', '统计数据已重置');
            } catch (error) {
              console.error('重置统计数据失败:', error);
              Alert.alert('错误', '重置统计数据失败');
            } finally {
              setLoading(false);
            }
          }
        }
      ]
    );
  };

  // 导出统计数据
  const handleExportStats = async () => {
    try {
      setLoading(true);
      const exportData = await statisticsService.exportData();
      
      // 这里可以集成文件保存功能
      console.log('导出统计数据:', exportData);
      
      Alert.alert('成功', '统计数据已导出到日志');
    } catch (error) {
      console.error('导出统计数据失败:', error);
      Alert.alert('错误', '导出统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 清理过期数据
  const handleCleanupData = async () => {
    try {
      setLoading(true);
      const cleaned = await statisticsService.cleanupOldData();
      await loadStatistics();
      
      Alert.alert('成功', `已清理 ${cleaned} 条过期数据`);
    } catch (error) {
      console.error('清理数据失败:', error);
      Alert.alert('错误', '清理数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 格式化时间
  const formatTime = (milliseconds) => {
    const seconds = Math.floor(milliseconds / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    
    if (hours > 0) {
      return `${hours}小时${minutes % 60}分钟`;
    } else if (minutes > 0) {
      return `${minutes}分钟${seconds % 60}秒`;
    } else {
      return `${seconds}秒`;
    }
  };

  // 获取平台颜色
  const getPlatformColor = (platform) => {
    const colors = {
      douyin: '#FF6B6B',
      kuaishou: '#4ECDC4',
      xigua: '#45B7D1',
      bilibili: '#96CEB4',
      weishi: '#FFEAA7',
      local: '#DDA0DD'
    };
    return colors[platform] || '#95A5A6';
  };

  // 生成平台分布饼图数据
  const getPlatformChartData = () => {
    if (!stats || !stats.platforms.length) return null;
    
    const platformStats = stats.platforms.filter(p => p.scrolls > 0);
    const totalScrolls = platformStats.reduce((sum, p) => sum + p.scrolls, 0);
    
    return {
      labels: platformStats.map(p => p.platform),
      datasets: [{
        data: platformStats.map(p => p.scrolls),
        colors: platformStats.map(p => getPlatformColor(p.platform)),
        strokeWidth: 2
      }],
      legend: platformStats.map(p => `${p.platform} (${Math.round((p.scrolls / totalScrolls) * 100)}%)`)
    };
  };

  // 生成每日趋势折线图数据
  const getDailyChartData = () => {
    if (!stats || !stats.daily.length) return null;
    
    const dailyData = stats.daily.slice(0, 7).reverse();
    
    return {
      labels: dailyData.map(d => d.date.split('-').slice(1).join('/')),
      datasets: [{
        data: dailyData.map(d => d.scrolls),
        color: (opacity = 1) => `rgba(76, 175, 80, ${opacity})`,
        strokeWidth: 2
      }],
      legend: ['每日滑动次数']
    };
  };

  // 生成使用时长柱状图数据
  const getTimeChartData = () => {
    if (!stats || !stats.daily.length) return null;
    
    const dailyData = stats.daily.slice(0, 7).reverse();
    
    return {
      labels: dailyData.map(d => d.date.split('-').slice(1).join('/')),
      datasets: [{
        data: dailyData.map(d => Math.round(d.time / 60000)), // 转换为分钟
        colors: dailyData.map(() => '#3498DB')
      }],
      legend: ['使用时长（分钟）']
    };
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#4CAF50" />
        <Text style={styles.loadingText}>正在加载统计数据...</Text>
      </View>
    );
  }

  if (!stats) {
    return (
      <View style={styles.emptyContainer}>
        <Text style={styles.emptyText}>暂无统计数据</Text>
        <Text style={styles.emptySubtext}>开始使用应用来生成统计数据</Text>
      </View>
    );
  }

  return (
    <ScrollView style={styles.container}>
      <View style={styles.header}>
        <Text style={styles.title}>使用统计</Text>
        <Text style={styles.subtitle}>查看您的使用数据</Text>
      </View>

      {/* 总览统计 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>总览统计</Text>
        <View style={styles.statsGrid}>
          <View style={styles.statCard}>
            <Text style={styles.statNumber}>{stats.summary.totalScrolls}</Text>
            <Text style={styles.statLabel}>总滑动次数</Text>
          </View>
          <View style={styles.statCard}>
            <Text style={styles.statNumber}>{formatTime(stats.summary.totalTime)}</Text>
            <Text style={styles.statLabel}>总使用时间</Text>
          </View>
          <View style={styles.statCard}>
            <Text style={styles.statNumber}>{stats.summary.averageScrollsPerMinute}</Text>
            <Text style={styles.statLabel}>平均速度（次/分钟）</Text>
          </View>
          <View style={styles.statCard}>
            <Text style={styles.statNumber}>{stats.platforms.length}</Text>
            <Text style={styles.statLabel}>使用平台数</Text>
          </View>
        </View>
      </View>

      {/* 使用趋势 */}
      {stats.trend && (
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>使用趋势</Text>
          <View style={styles.trendContainer}>
            <View style={styles.trendItem}>
              <Text style={styles.trendLabel}>滑动趋势</Text>
              <Text style={[
                styles.trendValue,
                stats.trend.scrollTrend > 0 && styles.trendUp,
                stats.trend.scrollTrend < 0 && styles.trendDown
              ]}>
                {stats.trend.scrollTrend > 0 ? '+' : ''}{stats.trend.scrollTrend.toFixed(1)}%
              </Text>
            </View>
            <View style={styles.trendItem}>
              <Text style={styles.trendLabel}>时间趋势</Text>
              <Text style={[
                styles.trendValue,
                stats.trend.timeTrend > 0 && styles.trendUp,
                stats.trend.timeTrend < 0 && styles.trendDown
              ]}>
                {stats.trend.timeTrend > 0 ? '+' : ''}{stats.trend.timeTrend.toFixed(1)}%
              </Text>
            </View>
          </View>
        </View>
      )}

      {/* 图表选择 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>数据可视化</Text>
        <View style={styles.chartTabs}>
          <TouchableOpacity
            style={[styles.chartTab, chartType === 'daily' && styles.chartTabActive]}
            onPress={() => setChartType('daily')}
          >
            <Text style={[styles.chartTabText, chartType === 'daily' && styles.chartTabTextActive]}>
              每日趋势
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.chartTab, chartType === 'platform' && styles.chartTabActive]}
            onPress={() => setChartType('platform')}
          >
            <Text style={[styles.chartTabText, chartType === 'platform' && styles.chartTabTextActive]}>
              平台分布
            </Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={[styles.chartTab, chartType === 'time' && styles.chartTabActive]}
            onPress={() => setChartType('time')}
          >
            <Text style={[styles.chartTabText, chartType === 'time' && styles.chartTabTextActive]}>
              使用时长
            </Text>
          </TouchableOpacity>
        </View>

        {/* 图表显示 */}
        <View style={styles.chartContainer}>
          {chartType === 'daily' && getDailyChartData() && (
            <LineChart
              data={getDailyChartData()}
              width={screenWidth - 64}
              height={200}
              chartConfig={{
                backgroundColor: '#FFFFFF',
                backgroundGradientFrom: '#FFFFFF',
                backgroundGradientTo: '#FFFFFF',
                decimalPlaces: 0,
                color: (opacity = 1) => `rgba(76, 175, 80, ${opacity})`,
                labelColor: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
                style: {
                  borderRadius: 16
                },
                propsForDots: {
                  r: '6',
                  strokeWidth: '2',
                  stroke: '#4CAF50'
                }
              }}
              bezier
              style={{
                marginVertical: 8,
                borderRadius: 16
              }}
            />
          )}

          {chartType === 'platform' && getPlatformChartData() && (
            <PieChart
              data={getPlatformChartData()}
              width={screenWidth - 64}
              height={200}
              chartConfig={{
                backgroundColor: '#FFFFFF',
                backgroundGradientFrom: '#FFFFFF',
                backgroundGradientTo: '#FFFFFF',
                color: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
                labelColor: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
                style: {
                  borderRadius: 16
                }
              }}
              accessor="population"
              backgroundColor="transparent"
              paddingLeft="15"
              absolute
            />
          )}

          {chartType === 'time' && getTimeChartData() && (
            <BarChart
              data={getTimeChartData()}
              width={screenWidth - 64}
              height={200}
              chartConfig={{
                backgroundColor: '#FFFFFF',
                backgroundGradientFrom: '#FFFFFF',
                backgroundGradientTo: '#FFFFFF',
                decimalPlaces: 0,
                color: (opacity = 1) => `rgba(52, 152, 219, ${opacity})`,
                labelColor: (opacity = 1) => `rgba(0, 0, 0, ${opacity})`,
                style: {
                  borderRadius: 16
                }
              }}
              style={{
                marginVertical: 8,
                borderRadius: 16
              }}
            />
          )}
        </View>
      </View>

      {/* 平台详情 */}
      {stats.platforms.length > 0 && (
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>平台详情</Text>
          {stats.platforms.map((platform) => (
            <View key={platform.platform} style={styles.platformItem}>
              <View style={styles.platformHeader}>
                <Text style={styles.platformName}>{platform.platform}</Text>
                <Text style={styles.platformLastUsed}>
                  最后使用: {new Date(platform.lastUsed).toLocaleDateString()}
                </Text>
              </View>
              <View style={styles.platformStats}>
                <View style={styles.platformStat}>
                  <Text style={styles.platformStatLabel}>滑动次数</Text>
                  <Text style={styles.platformStatValue}>{platform.scrolls}</Text>
                </View>
                <View style={styles.platformStat}>
                  <Text style={styles.platformStatLabel}>使用时长</Text>
                  <Text style={styles.platformStatValue}>{formatTime(platform.time)}</Text>
                </View>
                <View style={styles.platformStat}>
                  <Text style={styles.platformStatLabel}>平均速度</Text>
                  <Text style={styles.platformStatValue}>
                    {platform.averageScrollsPerMinute}次/分钟
                  </Text>
                </View>
              </View>
            </View>
          ))}
        </View>
      )}

      {/* 操作按钮 */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>数据管理</Text>
        <TouchableOpacity style={styles.actionButton} onPress={handleExportStats}>
          <Text style={styles.actionButtonText}>导出统计数据</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.actionButton} onPress={handleCleanupData}>
          <Text style={styles.actionButtonText}>清理过期数据</Text>
        </TouchableOpacity>
        <TouchableOpacity style={[styles.actionButton, styles.dangerButton]} onPress={handleResetStats}>
          <Text style={[styles.actionButtonText, styles.dangerButtonText]}>重置统计数据</Text>
        </TouchableOpacity>
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5F5F5',
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: '#666',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5F5F5',
  },
  emptyText: {
    fontSize: 18,
    color: '#666',
    marginBottom: 8,
  },
  emptySubtext: {
    fontSize: 14,
    color: '#999',
  },
  header: {
    backgroundColor: '#4CAF50',
    padding: 24,
    paddingTop: 40,
    alignItems: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#FFFFFF',
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 14,
    color: '#E8F5E8',
  },
  section: {
    backgroundColor: '#FFFFFF',
    marginHorizontal: 16,
    marginVertical: 8,
    borderRadius: 12,
    padding: 16,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 16,
  },
  statsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  statCard: {
    backgroundColor: '#F8F9FA',
    padding: 16,
    borderRadius: 12,
    marginBottom: 12,
    width: '48%',
    alignItems: 'center',
  },
  statNumber: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#4CAF50',
    marginBottom: 4,
  },
  statLabel: {
    fontSize: 12,
    color: '#666',
    textAlign: 'center',
  },
  trendContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  trendItem: {
    alignItems: 'center',
  },
  trendLabel: {
    fontSize: 14,
    color: '#666',
    marginBottom: 4,
  },
  trendValue: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
  trendUp: {
    color: '#4CAF50',
  },
  trendDown: {
    color: '#FF4444',
  },
  chartTabs: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 16,
  },
  chartTab: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
    backgroundColor: '#F5F5F5',
  },
  chartTabActive: {
    backgroundColor: '#4CAF50',
  },
  chartTabText: {
    fontSize: 14,
    color: '#666',
  },
  chartTabTextActive: {
    color: '#FFFFFF',
    fontWeight: 'bold',
  },
  chartContainer: {
    alignItems: 'center',
  },
  platformItem: {
    backgroundColor: '#F8F9FA',
    padding: 16,
    borderRadius: 12,
    marginBottom: 12,
  },
  platformHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 12,
  },
  platformName: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
  },
  platformLastUsed: {
    fontSize: 12,
    color: '#666',
  },
  platformStats: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  platformStat: {
    alignItems: 'center',
    flex: 1,
  },
  platformStatLabel: {
    fontSize: 12,
    color: '#666',
    marginBottom: 4,
  },
  platformStatValue: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#4CAF50',
  },
  actionButton: {
    backgroundColor: '#4CAF50',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderRadius: 8,
    marginVertical: 4,
    alignItems: 'center',
  },
  actionButtonText: {
    color: '#FFFFFF',
    fontSize: 14,
    fontWeight: 'bold',
  },
  dangerButton: {
    backgroundColor: '#FF4444',
  },
  dangerButtonText: {
    color: '#FFFFFF',
  },
});

export default StatisticsScreen;